package com.zhijiaoyun.common;

import java.util.Base64;
import java.util.Calendar;
import java.util.Date;

import com.shisfish.util.EmailUtils;
import com.zhijiaoyun.model.User;

/**
 * @author shisfish
 * @date 2017/12/14
 */
public class EmailModal {
	
	public static String URL = "http://www.zhijiaolearn.com/";

	public static String PROJECT_NAME = "zhijiaoyun-java";

	public static String createRegisterModal(String code) {
		StringBuffer sb = new StringBuffer("点击下面链接激活账号，24小时生效，否则重新注册账号，链接只能使用一次，请尽快激活！</br>");
		sb.append("<a href=\"" + URL + PROJECT_NAME + "/api/user/register?action=email&code=");
		sb.append(code);
		sb.append("\">" + URL + PROJECT_NAME + "/api/user/register?action=email&code=");
		sb.append(code);
		sb.append("</a>");
		return sb.toString();
	}

	public static String createForgetPasswordModal(String code) {
		StringBuffer sb = new StringBuffer("点击下面链接去修改密码，1小时生效，链接只能使用一次，请尽快激活！</br>");
		sb.append("<a href=\"" + URL + PROJECT_NAME + "/api/user/forgetPasswordConfirm?action=forgetPassword&code=");
		sb.append(code);
		sb.append("\">" + URL + PROJECT_NAME + "/api/user/forgetPasswordConfirm?action=forgetPassword&code=");
		sb.append(code);
		sb.append("</a>");
		return sb.toString();
	}

	public static String createCode(String email) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		cal.add(Calendar.HOUR_OF_DAY, 1);
		String json = "{\"email\": \"" + email + "\", \"expDate\": \"" + cal.getTimeInMillis() + "\"}";
		return json;
	}

	public static String createCode(String email, User user) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		cal.add(Calendar.DAY_OF_YEAR, 1);
		String json = "{\"email\": \""
				+ email + "\", \"username\": \""
				+ user.getUsername() + "\", \"realname\": \""
				+ user.getRealname() + "\", \"password\": \""
				+ user.getPassword() + "\", \"sex\": "
				+ user.getSex() + ", \"status\": "
				+ user.getStatus() + ", \"expDate\": "
				+ cal.getTimeInMillis() + "}";
		return json;
	}

	public static String createCode1(String email, User user) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		cal.add(Calendar.DAY_OF_YEAR, 1);
		String jsonString = JSONUtils.object2JsonString(user);
		return  "{\"expDate\": " + cal.getTimeInMillis() + ", \"user\": " + jsonString + "}";
	}

	public static String encodeCode(String code) {
		return Base64.getEncoder().encodeToString(code.getBytes());
	}

	public static String createEncodeCode1(String content) {
		return encodeCode(content);
	}

	public static String createEncodeCode(String email) {
		return encodeCode(createCode(email));
	}

	public static String createEncodeCode(String email, User user) {
		return encodeCode(createCode(email, user));
	}

	public static void sendEmail(String receiveMail, User user) throws Exception {
		String code = createEncodeCode(receiveMail, user);

		String content = createRegisterModal(code);

		EmailUtils.sendEmail(receiveMail, content);
	}
	
}
